from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()
# Create your models here.
class ChatRoom(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(max_length=200, blank=True, null=True)
    creator = models.ForeignKey(User,on_delete=models.CASCADE,related_name='create_rooms')
    create_time = models.DateTimeField(auto_now_add=True)
    is_activate = models.BooleanField(default=True)
    members = models.ManyToManyField(User,related_name='joined_rooms')
    block_users = models.ManyToManyField(User,related_name='block_rooms')

    # def __str__(self):
    #     return self.name

    def user_can_join(self,user):
        """检查用户能否加入聊天室"""
        # if user.is_authenticated and not self.members.contains(user) and not self.block_users.contains(user):
        if user.is_authenticated and not self.block_users.contains(user):
            return True
        else:
            return False
    def add_member(self,user):
        """记得先判断房间用户里是否与当前加的用户重复，记得判断一下"""
        if user.is_authenticated and not self.members.contains(user):
            self.members.add(user)
            return True
        return False
    def remove_member(self,user):
        if user.is_authenticated and self.members.contains(user):
            self.members.remove(user)
            return True
        return False
    def add_block(self,user):
        if user.is_authenticated and user:
            self.block_users.add(user)
            return True
        return False
    def deepseek_user(self):
        return User.objects.get_or_create(
            username='DeepSeekBot',
            defaults={
                'is_active': False,
                'is_staff': False,
                'is_superuser': False
            }  # 如果不用defaults，模型里的其他字段可能重复 会报错
        )[0]  # get_or_create返回两个值，一个模型值和一个是否创建的值bool


class RoomMessage(models.Model):
    room = models.ForeignKey(ChatRoom,on_delete=models.CASCADE,related_name='room_messages')
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user_room_messages')
    content = models.TextField(max_length=500)
    timestamp = models.DateTimeField(auto_now_add=True)
    is_deepseek = models.BooleanField(default=False)

    class Meta:
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['room','timestamp'])
            # 根据房间和时间来快速索引聊天记录
        ]

    def __str__(self):
        return f"{self.user.username}: {self.content[:50]}"